package com.by.springboottwodatabases.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.by.springboottwodatabases.controller.request.OneRequestBean;
import com.by.springboottwodatabases.controller.request.TestRequestBean;
import com.by.springboottwodatabases.domain.one.DOne;
import com.by.springboottwodatabases.domain.one.DTestOne;
import com.by.springboottwodatabases.domain.one.repository.DOneRepository;
import com.by.springboottwodatabases.domain.one.repository.DTestOneRepository;
import com.by.springboottwodatabases.service.OneService;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class OneServiceImpl implements OneService {

    private final DOneRepository oneRepository;
    private final DTestOneRepository testRepository;

    public OneServiceImpl(DOneRepository oneRepository, DTestOneRepository testRepository) {
        this.oneRepository = oneRepository;
        this.testRepository = testRepository;
    }

    @Override
    public DOne createOne(OneRequestBean bean) {
        DOne one = new DOne();
        BeanUtil.copyProperties(bean, one, true);
        return oneRepository.save(one);
    }

    @Override
    public DOne findById(Long id) {
        Optional<DOne> one = oneRepository.findById(id);
        return one.orElse(null);
    }

    @Override
    public DOne updateOne(Long id, OneRequestBean bean) {
        DOne one = findById(id);
        BeanUtil.copyProperties(bean, one, true);
        return oneRepository.save(one);
    }

    @Override
    public void deleteOne(Long id) {
        oneRepository.deleteById(id);
    }

    @Override
    public DTestOne createTest(TestRequestBean bean) {
        DTestOne test = new DTestOne();
        BeanUtil.copyProperties(bean, test, true);
        return testRepository.save(test);
    }

    @Override
    public DTestOne findTestById(Long id) {
        Optional<DTestOne> one = testRepository.findById(id);
        return one.orElse(null);
    }

    @Override
    public DTestOne updateTest(Long id, TestRequestBean bean) {
        DTestOne test = findTestById(id);
        BeanUtil.copyProperties(bean, test, true);
        return testRepository.save(test);
    }

    @Override
    public void deleteTest(Long id) {
        testRepository.deleteById(id);
    }


}
